package com.itgaohe.controller;


import com.itgaohe.utils.AliyunOssUtil;
import com.itgaohe.utils.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("upload")
@Tag(name = "OSS图片上传", description = "用户相关操作")
public class UploadController {

    private final AliyunOssUtil aliyunOssUtil;

    public UploadController(AliyunOssUtil aliyunOssUtil) {
        this.aliyunOssUtil = aliyunOssUtil;
    }

    @Operation(summary = "上传图片")
    @PostMapping("blog")
    public Result uploadImage(@RequestParam("file") MultipartFile image) {
        try {
            // 生成新文件名
            String fileName = createNewFileName(image.getOriginalFilename());
            // 上传到OSS
            String url = aliyunOssUtil.uploadFile(image, "images");
            // 返回结果
            log.debug("文件上传成功，文件名: {}", fileName);
            return Result.ok(url);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return Result.fail("文件上传失败，请稍后重试");
        }
    }

    @Operation(summary = "删除图片")
    @GetMapping("/image/delete")
    public Result deleteImage(@RequestParam("url") String url) {
        try {
            // 从URL中提取objectName
            String objectName = extractObjectName(url);
            if (objectName == null) {
                return Result.fail("无效的URL");
            }
            // 删除OSS文件
            aliyunOssUtil.deleteFile(objectName);
            return Result.ok();
        } catch (Exception e) {
            log.error("文件删除失败", e);
            return Result.fail("文件删除失败，请稍后重试");
        }
    }

    private String createNewFileName(String originalFilename) {
        // 获取后缀
        String suffix = getFileExtension(originalFilename);
        // 生成唯一名称
        String uuid = UUID.randomUUID().toString();
        // 生成目录结构 (使用UUID的哈希值创建两级目录)
        int hash = uuid.hashCode();
        int dir1 = hash & 0xF; // 0-15
        int dir2 = (hash >> 4) & 0xF; // 0-15
        // 返回格式化的文件名 (包含目录)
        return String.format("images/%d/%d/%s.%s", dir1, dir2, uuid, suffix);
    }

    private String getFileExtension(String filename) {
        if (filename == null || !filename.contains(".")) {
            return "";
        }
        return filename.substring(filename.lastIndexOf(".") + 1);
    }

    private String extractObjectName(String url) {
        if (url == null) return null;
        // 从URL中提取objectName部分
        // 假设URL格式为: https://bucket.endpoint/objectName
        int index = url.indexOf(aliyunOssUtil.getBucketName() + "." + aliyunOssUtil.getEndpoint());
        if (index == -1) return null;
        index = url.indexOf("/", index + (aliyunOssUtil.getBucketName() + "." + aliyunOssUtil.getEndpoint()).length());
        if (index == -1) return null;
        return url.substring(index + 1);
    }
}